package com.example.kotlinnote

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.kotlinnote.entity.NoteBean
import com.example.kotlinnote.picker.SinglePickUtil
import com.example.kotlinnote.ui.NoteAdapter
import com.example.kotlinnote.ui.NoteGridAdapter
import com.example.kotlinnote.ui.WriteNoteActivity
import com.example.kotlinnote.ui.db.SQLiteDB
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*

class MainActivity : AppCompatActivity(), View.OnClickListener {

    private val mNoteBeanList: MutableList<NoteBean> = ArrayList()
    private var isFirst = true
    private val mOrderBys = Arrays.asList("编辑日期", "创建日期", "标题")
    private var mOrderBy = "update_time"
    private var mNoteAdapter: NoteAdapter? = null
    private var mNoteGridAdapter: NoteGridAdapter? = null
    private var isRecycview = true
    private var mActivity: Activity? = null
    public override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        iv_add_note.setOnClickListener(this)
        tv_order_by.setOnClickListener(this)
        iv_switch_view.setOnClickListener(this)
        mActivity = this
        initAdapter()
        edit_search_context!!.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
            override fun afterTextChanged(s: Editable) {
                mNoteBeanList.clear()
                mNoteBeanList.addAll(
                    SQLiteDB.getInstance(mActivity)!!
                        .findDataByContent(s.toString(), mOrderBy)
                )
                if (isRecycview) {
                    mNoteAdapter!!.notifyDataSetChanged()
                } else {
                    mNoteGridAdapter!!.notifyDataSetChanged()
                }
            }
        })
        updateView()
        core_list_refresh_id!!.isEnabled = false
    }

    private fun loadData() {
        mNoteBeanList.clear()
        mNoteBeanList.addAll(SQLiteDB.getInstance(mActivity)!!.findAllData(mOrderBy))
        tv_note_count!!.text = String.format("%s个备忘录", mNoteBeanList.size)
        if (isRecycview) {
            mNoteAdapter!!.notifyDataSetChanged()
        } else {
            mNoteGridAdapter!!.notifyDataSetChanged()
        }
    }

    override fun onResume() {
        if (!isFirst) {
            loadData()
        }
        isFirst = false
        super.onResume()
    }

    override fun onClick(view: View) {
        when (view.id) {
            R.id.iv_add_note -> {
                val intent = Intent(mActivity, WriteNoteActivity::class.java)
                intent.putExtra(
                    WriteNoteActivity.EXTRA_TYPE,
                    WriteNoteActivity.EXTRA_ADD
                )
                startActivity(intent)
            }
            R.id.tv_order_by -> {
                val singlePickUtil = SinglePickUtil(mActivity)
                singlePickUtil.show()
                val textView = singlePickUtil.findViewById<TextView>(R.id.tv_title)
                textView.text = ""
                singlePickUtil.resetData(mOrderBys)
                singlePickUtil.setOnSelectedPositionListener(object :
                    SinglePickUtil.OnSelectedPositionListener {
                    override fun onSelected(selectedValue: Any?, position: Int) {
                        tv_order_by!!.text = String.format("按%s排序", selectedValue.toString())
                        when (position) {
                            0 -> mOrderBy = "update_time"
                            1 -> mOrderBy = "add_time"
                            2 -> mOrderBy = "title"
                        }
                        loadData()
                    }

                }

                )
            }
            R.id.iv_switch_view -> {
                isRecycview = !isRecycview
                updateView()
            }
        }
    }

    private fun updateView() {
        if (!isRecycview) {
            core_list_view_id!!.layoutManager = GridLayoutManager(mActivity, 3)
            core_list_view_id!!.adapter = mNoteGridAdapter
            loadData()
        } else {
            core_list_view_id!!.layoutManager = LinearLayoutManager(mActivity)
            core_list_view_id!!.adapter = mNoteAdapter
            loadData()
        }
    }

    /**
     * 初始化两个适配器
     */
    private fun initAdapter() {
        mNoteGridAdapter = NoteGridAdapter(mNoteBeanList)
        mNoteAdapter = NoteAdapter(mNoteBeanList)
        mNoteAdapter!!.addChildClickViewIds(R.id.tv_delete)
        mNoteGridAdapter!!.setOnItemClickListener { adapter, view, position -> goToUpdate(position) }
        mNoteAdapter!!.setOnItemClickListener { adapter, view, position -> goToUpdate(position) }
        mNoteAdapter!!.setOnItemChildClickListener { adapter, view, position ->
            val noteBean = mNoteAdapter!!.getItem(position)
            if (view.id == R.id.tv_delete) {
                if (SQLiteDB.getInstance(mActivity)!!.deleteNote(noteBean.note_id)) {
                    loadData()
                } else {
                    Toast.makeText(mActivity, "删除失败", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    private fun goToUpdate(position: Int) {
        val noteBean = mNoteBeanList[position]
        val intent = Intent(mActivity, WriteNoteActivity::class.java)
        intent.putExtra(
            WriteNoteActivity.EXTRA_TYPE,
            WriteNoteActivity.EXTRA_UPDATE
        )
        intent.putExtra(WriteNoteActivity.EXTRA_CONTENT, noteBean.content)
        intent.putExtra(WriteNoteActivity.EXTRA_TITLE, noteBean.title)
        intent.putExtra(WriteNoteActivity.EXTRA_ID, noteBean.note_id)
        startActivity(intent)
    }
}